/*
 * Copyright (c) Huawei Device Co., Ltd. 2024. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ef_dir.h"

#include "der_parser.h"
#include "loghelper.h"

namespace OHOS {
namespace SE {
// reference: GlobalPlatform Device Technology Secyre Element Access Control Spec.
const std::vector<uint8_t> DEFAULT_EFDIR_PATH = {0x3F, 0x00, 0x2F, 0x00};

EfDir::EfDir() : EfParser()
{
}

EfDir::~EfDir()
{
}

std::vector<uint8_t> EfDir::GetOdfPath(const std::vector<uint8_t> &data, const std::vector<uint8_t> &aid)
{
    std::shared_ptr<DerParser> der = std::make_shared<DerParser>(data);
    der->GetTlvDataLength(ASN1_APPL_TEMPLATE);
    der->GetTlvDataLength(ASN1_APPL_IDENTIFIER);
    if (der->GetTlvData() == aid) {
        return std::vector<uint8_t>();
    }

    uint8_t type = der->GetTlvType();
    if (type == ASN1_APPL_LABEL) {
        der->GetTlvData();
        der->GetTlvDataLength(ASN1_APPL_PATH);
    } else if (type != ASN1_APPL_PATH) {
        ErrorLog("Invalid dir data.");
        return std::vector<uint8_t>();
    }
    return der->GetTlvData();
}

std::vector<uint8_t> EfDir::ParseDirFileData(const std::vector<uint8_t> &aid)
{
    InfoLog("Parsing DIR file by aid.");

    std::vector<uint8_t> odfPath;
    uint16_t rspApdu = 0;
    if (!ReadFileByPath(DEFAULT_EFDIR_PATH, rspApdu)) {
        ErrorLog("fail to read ef dir file, rspApdu[%{public}x]", rspApdu);
        return odfPath;
    }

    for (uint8_t record = 1; record <= GetFileRecordNumber(); record++) {
        std::vector<uint8_t> data = ReadFileRecord(record);
        odfPath = GetOdfPath(data, aid);
        if (odfPath.size() == 0) {
            break;
        }
    }
    return odfPath;
}
}  // namespace SE
}  // namespace OHOS
